Introduction
Matplotlib is a plotting library for 2D graphics. It is used for creating static, animated, and interactive visualizations in Python. This is a kind of replacement for MATLAB. But if someone wishes to use MATLAB, then there are certain functions which are used to call Python functions from MATLAB. One of the examples is
matlab.engine.start_matlab (This would start the MATLAB engine for python.) Matplotlib is built on
NumPy array (to understand NumPy you can refer to -
https://www.c-sharpcorner.com/article/getting-started-with-numpy/ and
https://www.c-sharpcorner.com/article/numpy-array/ ), which is a multidimensional data visualization for 2D plots of arrays.
To import the library we use:
import matplotlib.pyplot
Comparison between MATLAB and MATPLOTLIB
As we get started with Matplotlib, we already mentioned that it is kind of replacement of MATLAB, so we should be aware of the challenges.
- So, MATLAB in some or other way is a global style and it contains various functions that do not needs import and are readily available at the top level.
- Since, Matplotlib is built on top of NumPy array it needs to incorporate NumPy routine as well. This is also a challenge.
- In Matplotlib, we have a module named, PYLAB- This brings all the classes and functions of NumPy and Matplotlib.pyplot together into a common namespace. Also, it clones the global nature of MATLAB.
Types of plots
- Line Plot- plot ()
- Bar Graph- bar ()
- Histogram- hist ()
- Scatter Plot- scatter ()
- Area plot- stackplot ()
- Pie plot-pie ()
Now let us understand how we plot these.
Line Plot/ Line Chart
This is a kind of Graph or Curve Chart which represents the information in the form of data points which are connected through straight lines.
We use function, plot()- to plot the line chart. It has 2 arguments in it, plot(x,y)- x coordinates to the x-axis, y is coordinates of the y-axis
EXAMPLE
- from matplotlib import pyplot as plt
-
- plt.plot([1,2,5],[5,8,7]) # Function to plot
- plt.show() # function to show the plot
So according to the above function plot (): 1st coordinates are (1,5), 2nd are (2,8) and 3rd are (5,7).
We can add as many coordinates we want; we can add title to a particular chart, we can also add title to the axis. For example,
- from matplotlib import pyplot as plt
-
- x = [5,2,7,5,9]
- y = [10,5,9,3,2]
-
- plt.plot(x,y)
- plt.title('Line Chart')
- plt.ylabel('Y axis')
- plt.xlabel('X axis')
- plt.show()
We can also plot a simple plot of angle in as well.
- from matplotlib import pyplot as plt
- import numpy as np
- import math
-
- x=np.arange(0, math.pi, 0.01)
- y=np.cos(x)
- plt.plot(x,y)
- plt.show()
We can plot more than one line into line chart, we can also make it colourful
Markers
‘.’ – point marker, ‘o’- circle, ‘*’- star, ‘^’- triangle_up, ‘p’- pentagon, ‘s’- square, ‘+’-plus, ‘D’- Diamond, ‘|’- vline …. And many more.
Colors
‘b’ -blue , ‘g’- green , ‘r’-red , ‘y’- yellow , ‘k’- black , ‘m’- magenta, ‘w’- white, ‘c’- cyan
Line styles
‘-‘ (solid line), ‘- -‘ (Dashed line) , ‘-.’ (Dash dot line) , ‘:’ (Dotted line)
We should use it in format '[marker][line][colour]'
- from matplotlib import pyplot as plt
- import numpy as np
- import math
-
- x1 = [1,17,27]
- y1 = [6,18,2]
-
- x2 = [6,9,30]
- y2 = [1,15,5]
-
- x3 = [5, 2, 25, 14, 30]
- y3 = [10, 4, 20, 8, 3]
-
- x=np.arange(0, math.pi*10, 0.10)
- y=np.sin(x)
-
- plt.plot(x1,y1,'g',label='line one')
- plt.plot(x2,y2,'c',label='line two',linewidth=5)
- plt.plot(x,y,'g--',label='sine wave')
- plt.plot(x3,y3,'m:',label='line three',linewidth=5)
- plt.title('Multiple Data')
- plt.ylabel('Price')
- plt.xlabel('Growth')
-
- plt.legend()
- plt.grid(True,color='k')
-
- plt.show()
Bar Plot
This type of plot is also known as Bar Chart or Bar Graph which is a graphical display of data using rectangular bars of different heights.
We use function, bar()- to plot the bar chart.
EXAMPLE
- from matplotlib import pyplot as plt
-
- x = [5, 2, 9, 4, 7]
- y = [10, 5, 8, 4, 2]
-
- plt.bar(x,y)
- plt.show()
You can change the color of the bars, change the width and height, can perform the comparison tasks, and all similar as above.
- from matplotlib import pyplot as plt
-
- plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
- label="2019", color='k',width=.5)
-
- plt.bar([0.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
- label="2020", color='m',width=.5)
-
- plt.legend()
- plt.xlabel('Months')
- plt.ylabel('Productivity (line of code)')
- plt.title('Associate Data')
-
- plt.show()
Histogram
This is a graphical display of data using bars of different heights. It is similar to a Bar Chart, but a histogram groups numbers into ranges.
We use function, hist()- to plot the Histogram
EXAMPLE
- import matplotlib.pyplot as plt
-
- population_age = [22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,111,115,80,75,65,54,44,43,42,48]
- bins = [0,10,20,30,40,50,60,70,80,90,100]
-
- plt.hist(population_age, bins,color='c', rwidth=0.8)
- plt.xlabel('Permanant Employees')
- plt.ylabel('Training (yrs)')
- plt.title('Histogram')
-
- plt.show()
Scatter Plot
A scatter plot or scatter graph, scatter chart, scatter gram, or scatter diagram is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data.
We use function, scatter()- to plot the scatter plot.
EXAMPLE
- import matplotlib.pyplot as plt
-
- x = [1,2,3,4,5,6,7]
- y = [3,4,5,6,6.5,7,8]
-
- x1=[8,8.5,9,9.5,10,10.5,11]
- y1=[3,3.5,3.7,4,4.5,5,5.2]
-
- x2 = [4,3,6,7,7.5,8,6.5,8,7.5,5,5.5]
- y2 = [4,4.5,5,6,5,4,4.5,4,6,5.5,4.5]
-
-
- plt.scatter(x,y, label='high income low saving',color='r')
- plt.scatter(x1,y1,label='low income high savings',color='b')
- plt.scatter(x2,y2,label='lone',color='m')
- plt.xlabel('saving*100')
- plt.ylabel('income*1000')
- plt.title('Scatter Plot')
- plt.legend()
-
- plt.show()
Area Plot
An Area plot/Chart is made by plotting a series of data points over time, connecting those data points with line segments, and then filling in the area between the line and the x-axis with color or shading.
We use function, stackplot()- to plot the area plot
EXAMPLE
- import matplotlib.pyplot as plt
-
- days = [1,2,3,4,5]
- sleeping =[7,8,6,11,7]
- eating = [2,3,4,3,2]
- working =[7,8,7,2,2]
- playing = [8,5,7,8,13]
-
- plt.plot([],[],color='m', label='Sleeping', linewidth=5)
- plt.plot([],[],color='c', label='Eating', linewidth=5)
- plt.plot([],[],color='k', label='Working', linewidth=5)
- plt.plot([],[],color='b', label='Playing', linewidth=5)
-
- plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','k','b'])
- plt.xlabel('Hours')
- plt.ylabel('Days')
- plt.title('Stack Plot')
- plt.legend()
-
- plt.show()
Pie Plot
A Pie Chart is in the form of a pie which is a circular statistical graph divided into slices to illustrate numerical proportion
We use function, pie()- to plot the pie plot.
Pie() function includes various arguments,
- Sizes - Sizes is the area in which a particular label will cover within a whole pie.
- Labels - Labels are the categories in which you want the pie chart to be divided into.
- Colors - Colours are specified w.r.t every label
- Startangle -This makes the plotting right in the top middle of the pie chart. The elements are plotted sequentially in a clockwise manner if we use startangle=90, if we use startangle=180; it would populate the first element on the top with a 180-degree angle and then goes counterclockwise.
- Shadow - This will add a shadow type outline to the pie chart, if shadow= True, if shadow= False; Then there would be no outline or shadow we will just see white spaces between the labels.
- Explode - This will explode out the slice from the pie chart like- explode= (0,0,0.1,0), This we explode out only the 3rd slice.
- Autopct - This will add percentages to each of the constituents of the pie chart, like if we use autopct='%1.2f%%' the percentage is formatted to the hundredths place, if we use autopct='%1.3f%%' the percentage is formatted to the thousandths place
EXAMPLE
Before wrapping up Matplotlib, we should be aware that it is very difficult to use Matplotlib in other languages as it is restricted to Python only; one of the major reasons could be that it is heavily reliant on NumPy Library.
SUMMARY
We learned about Matplotlib Library in Python which used to plot 2D graphics. Now practice plotting various graphs using the above information and apart from these plots, we can plot multiple plots. Do Practice!
I hope this article will help you further in Learning Python - Matplotlib.
Feedback or queries related to this article are most welcome.
Thanks for reading.